package demo;

import java.util.PriorityQueue;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 38917
 * Date: 2025-03-06
 * Time: 14:00
 */
class MyTask implements Comparable<MyTask>{
    private final Runnable runnable;
    private final long time;
    public MyTask(Runnable runnable,long delay){
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + delay;
    }
    public long getTime(){
        return this.time;
    }
    public void run(){
        runnable.run();
    }
    @Override
    public int compareTo(MyTask o) {
        return (int)(this.time - o.time);
    }
}
class MyTime{
    private final PriorityQueue<MyTask> queue = new PriorityQueue<>();
    public void schedule(Runnable runnable,long delay){
        synchronized (this) {
            MyTask myTask = new MyTask(runnable, delay);
            queue.offer(myTask);
            this.notify();
        }
    }
    public MyTime(){
        Thread thread = new Thread(() -> {
            while (true) {
                try {
                    synchronized (this) {
                        while (queue.isEmpty()) {
                            this.wait();
                        }
                        MyTask myTask = queue.peek();
                        long curTime = System.currentTimeMillis();
                        if (curTime >= myTask.getTime()) {
                            myTask.run();
                            queue.poll();
                        } else {
                            this.wait(myTask.getTime() - curTime);
                        }
                    }
                }catch (InterruptedException e){
                    throw new RuntimeException(e);
                }
            }
        });
        thread.setDaemon(true);
        thread.start();
    }
}

public class test {
    public static void main(String[] args) throws InterruptedException {
        MyTime myTime = new MyTime();
        myTime.schedule(()-> System.out.println("Hello " + 3000),3000);

        Thread.sleep(3500);
        System.out.println("Hello Main");
    }
}
